import React,{Component} from "react"

import BScroll  from "better-scroll";

import Login from "../../components/login"

import Tipmsg from "../../components/tipmsg"
import Loading from "../../components/loading"


import "./index.css"



import defaultImg from "../../images/default.png"

import {
  getcourselist,
  getDetail,
  getGoodWork,
  getComment,
  createComment,
  getUserInfo,
  LikeComment,
  UnLikeComment,
  authLogin,
  myWork
} from "../../api/course" 

import config from "../../api/config";
let {accessToken} = config;




    function toZero(n){
       if(n<10){
        return "0"+n
       }else{
        return ""+n;
       }
    }



    function toFormatDate(dateStr){
        //传入时间
        var date1 = dateStr.replace(/\-/ig,"/");
        date1 = date1.split("T")[0]+" "+  date1.split("T")[1].split(".")[0].split("Z")[0]
        //console.log(date1);
        var nowTime = new Date(date1).getTime()+8*60*60*1000
      
        var iDate = new Date(nowTime)
        var iYear = iDate.getFullYear();
        var iMonth = iDate.getMonth()+1;
        var iDay = iDate.getDate();
        var iH = iDate.getHours();
        var iM = iDate.getMinutes();
        var iS= iDate.getSeconds();

        return iYear+"/"+toZero(iMonth)+"/"+toZero(iDay)+" "+toZero(iH)+":"+toZero(iM)+":"+toZero(iS);
    }







class Index extends Component{
    constructor(props){
    	super(props);
    	this.state = {
        msg:"",
        loading:"",
        showLoading:false,
    		nowIndex:0,
        showmask:false,
        showload:false,
    		courselist:[],
    		worklist:[],
        mywork:[],
        commentlist:[],
        videoSrc:"",
        userimg:"",
        username:"",
        html:"",
        desc:"",
        title:"",
        CommentsCount:0,
        isLogin:false,
        page:0, //评论分页
        AppUserId:"",
        toggle:false,
        showTip:false,
        showBtn:false,
        isShow:false,
        tipmsg:"",
        htmlStr:"",
        showDown:false
      }
    }

   


    
    closeModal(){
      this.setState({isLogin:false})
    }

    LikeCommentHandl(id){
         
         if(localStorage.getItem("courseUserinfo")){
              let token = JSON.parse(localStorage.getItem("courseUserinfo")).AccessToken;
              this.setState({
                showload:true
              })
              LikeComment(token,id).then(res=>{
                  this.state.commentlist.forEach(item=>{
                       if(item.CommentId==id){
                          item.IsLiked = true;
                          item.LikesCount++;
                       }
                  })
                  this.setState({
                      commentlist:this.state.commentlist,
                      showload:false
                  })
     
              })
         }else{
             var ua = navigator.userAgent.toLowerCase();//获取判断用的对象
             if (ua.match(/MicroMessenger/i) == "micromessenger") {
                //在微信中打开
                window.WechatAuthorize();
                return 
             }
             if (ua.match(/WeiBo/i) == "weibo") {
                 //在新浪微博客户端打开
                 window.WeiboAuthorize();
                 return 
             }
             
             this.setState({
                isLogin:true
             })

         }
    }

    UnLikeCommentHandl(id){
          let token = JSON.parse(localStorage.getItem("courseUserinfo")).AccessToken;
          this.setState({
                showload:true
          }) 
          UnLikeComment(token,id).then(res=>{
              this.state.commentlist.forEach(item=>{
                  if(item.CommentId==id){
                     item.IsLiked = false;
                     item.LikesCount--;
                  }
              })
              
              this.setState({
                 commentlist:this.state.commentlist,
                 showload:false
              })
         })
         
    }
    
    

   

   



    toZero(n){
    	return n<10?"0"+n:""+n
    }
    

    closeHandl(){
      this.setState({showTip:false})
    }
    
    getCommentList(page){    //获取评论
  
       let token = localStorage.getItem("courseUserinfo") ? JSON.parse(localStorage.getItem("courseUserinfo")).AccessToken:accessToken;
       

       getComment(token,this.props.match.params.id,page)
       .then(res=>{
        
          this.setState({
              commentlist:[...this.state.commentlist,...res.data]
          })
       })
    }

    


    
    addComment(){ //提交评论
        if(localStorage.getItem("courseUserinfo")){
           if(this.state.msg.trim()==""){
              this.setState({
                showTip:true,
                tipmsg:"请输入评论"
             })
             return;
           }

           if(this.state.msg.trim().length>140){
             
              this.setState({
                showTip:true,
                tipmsg:"评论字数长度不得超过140"
              })
              return;
           }
           //已经登录
           let token =JSON.parse(localStorage.getItem("courseUserinfo")).AccessToken;
           
            this.setState({
                showload:true
            })

           getUserInfo(token).then(res=>{
               if(res.data.PhoneNumber!=""){//已经绑定手机号
                    /*this.setState({
                       showload:true
                      // loading:"提交评论中..."
                    })*/
                    let postid = this.props.match.params.id;
                    createComment(token,postid,{
                        "Text": this.state.msg
                    }).then(res=>{
                         console.log(res);
                         this.setState({
                          commentlist:[],
                          showload:false,
                          msg:"",
                          page:0,
                          showmask:false,
                          CommentsCount:this.state.CommentsCount+1
                         },()=>{
                          this.getCommentList(this.state.page)

                         })
                         
                    }).catch(err=>{
                        this.setState({
                           showload:false,
                           msg:"",
                           showTip:true,
                           tipmsg:"您的评论存在违禁词"
                        })
                    })
               }else{  //未手机号码
                  //alert("去绑定手机号码")
                  this.props.history.push("/fanscourse/bindphone")
               }
           })
        
        }else{  //没有登录
             var ua = navigator.userAgent.toLowerCase();//获取判断用的对象
             if (ua.match(/MicroMessenger/i) == "micromessenger") {
                //在微信中打开
                window.WechatAuthorize();
                return 
             }
             if (ua.match(/WeiBo/i) == "weibo") {
               //在新浪微博客户端打开
                 window.WeiboAuthorize();
                 return 
             }
             
             this.setState({
                isLogin:true
             })
       }

    }
    

    componentWillMount(){
          this.getDetailData();
    }

    componentDidMount(){
    	  
        this.getcourseData();
       // this.getDetailData();
        this.getGoodWorkList();
        this.getCommentList(0);
        this.getMywork();
        this.init();

        if(JSON.parse(localStorage.getItem("courseUserinfo"))){
            this.setState({
               AppUserId:JSON.parse(localStorage.getItem("courseUserinfo")).AppUserId
            })
               
        }else{
            this.setState({
              AppUserId:""
            })
        }
   
    }

    init(){
       this.courselist = new BScroll(this.refs.courselist,{
            scrollY: false,
            scrollX: true,
            useTransition:false,
            click: true
        })

        this.worklist = new BScroll(this.refs.worklist,{
            scrollY: false,
            scrollX: true,
            useTransition:false,
            click: true
        })

       /* this.myworklist = new BScroll(this.refs.myworklist,{
            scrollY: false,
            scrollX: true,
            useTransition:false,
            click: true
        })*/
    }


    getGoodWorkList(){  //获取优秀作业
      if(localStorage.getItem("courseUserinfo")){
         let {AppUserId} = JSON.parse(localStorage.getItem("courseUserinfo"));
         getGoodWork(this.props.match.params.id).then(res=>{
          res.data.forEach((item,index)=>{
              if(item.AppUserId==AppUserId){
                  res.data.unshift(res.data.splice(index,1)[0])
              }
          })
          this.setState({worklist:res.data})
        })
      }else{
        getGoodWork(this.props.match.params.id).then(res=>{
        /*  res.data.forEach((item,index)=>{
              if(item.AppUserId==AppUserId){
                  res.data.unshift(res.data.splice(index,1)[0])
              }
          })*/
          this.setState({worklist:res.data})
        })
      }
     
     
      
    }

    getMywork(){  //获取我得作业
       if(localStorage.getItem("courseUserinfo")){
         let {AppUserId,AccessToken} = JSON.parse(localStorage.getItem("courseUserinfo"))
         let {id} = this.props.match.params;
         myWork(id,AccessToken,AppUserId).then(res=>{
           // console.log(res.data)
            this.setState({
               mywork:res.data
            })
         })
       }
      
    }

    getcourseData(){  //获取课程系列
      getcourselist(this.props.match.params.id).then(res=>{
   
             if(JSON.parse(res.data.data.data).length!=0){
                  let data = JSON.parse(res.data.data.data)[0];
                 // console.log(data.addItemList)
                  this.setState({
                     userimg:data.imgurl,
                     username:data.coursetutor,
                     courselist:data.addItemList,
                     videoSrc:data.addItemList[0].link
                  })
             }
             
      })
    }
    
    getDetailData(){  //获取详情信息
      //console.log(this.props)
      getDetail(this.props.match.params.id).then(res=>{
          this.setState({
             // html:res.data.Html?res.data.Html.substring(0,26):"",
              html:res.data.Html?res.data.Html:"",
              
              showDown:res.data.Html?true:false,
              htmlStr:res.data.Html?res.data.Html:"",
              title:res.data.Title,
              CommentsCount:res.data.CommentsCount,
              desc:res.data.Description ? res.data.Description:"暂无内容"
          },()=>{
              this.refs.htmlbox.style.height = "0.4rem"
          })
        
          let {SubmitPostStartDate,SubmitPostEndDate} = res.data.PostContestInfo;
       
          let startTime = new Date(toFormatDate(SubmitPostStartDate)).getTime();
          let endTime = new Date(toFormatDate(SubmitPostEndDate)).getTime();
          let nowTime = new Date().getTime();
          /*console.log(startTime)
            console.log(endTime)
            console.log(nowTime)*/
          console.log(nowTime>=startTime && nowTime<=endTime)
          if(nowTime>=startTime && nowTime<=endTime){
              this.setState({
                showBtn:true,
                isShow:true
              })
           
          }else if(nowTime>endTime){
              this.setState({
                showBtn:false,
                isShow:true
              })
          }else if(nowTime<startTime){
             this.setState({
               isShow:false
             })
          }

         
          var shareLink="https://games.ixingban.com/fanscourse/#/detail/"+this.props.match.params.id;
          // var shareLink = "#";
          //alert(shareLink);
          window.WechatInit(encodeURIComponent(window.location.href)).then(wx=>{
              //alert(JSON.stringify(wx))
              //alert(window.location.href)
              var shareOptions = { 
                  title:res.data.Title, // 分享标题
                  desc:res.data.Description ? res.data.Description:"暂无内容", // 分享描述
                  link:window.location.href,//window.location.href,//"https://games.ixingban.com/fanscourse/#/detail/"+180018//window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                  imgUrl: res.data.PhotoList[0].ThumbnailUrl, // 分享图标
                  success: function (res) {
                     //alert(JSON.stringify(res))
                     //console.log(res);
                  }
              }
              
              if(wx){
                 wx.updateAppMessageShareData(shareOptions);
                 wx.updateTimelineShareData(shareOptions);
                 wx.onMenuShareWeibo(shareOptions);
              }
          })


      })
    }


    loadComment(){
        this.commentwrap = new BScroll(this.refs.commentwrap,{
               scrollY: true,
               scrollX: false,
               useTransition:false,
               click: true,
               pullUpLoad: {
                    threshold:-20 
               },
               pullDownRefresh: {
                     threshold:30,
                     stop: 0
               }
        })


        this.commentwrap.on('pullingUp',()=>{
          
            this.setState({
               page:this.state.page+10
            },()=>{
              this.getCommentList(this.state.page)
            })
            
            setTimeout(() => {
                this.commentwrap.finishPullUp();
                this.commentwrap.refresh();
            },500)
         
        })
    }


    
    

    changeCourselist(nowIndex,link){ //切换视频
    	  this.setState({
            nowIndex,
            videoSrc:link
        },()=>{
          //this.refs.video.play()
        })
    }

    toPost(){
        if(localStorage.getItem("courseUserinfo")){
              if(this.state.showBtn){
                    this.props.history.push("/fanscourse/postwork/"+this.props.match.params.id)
              }else{
                    this.setState({
                        showTip:true,
                        tipmsg:"交作业时间已结束"
                    })
              }
        }else{
              var ua = navigator.userAgent.toLowerCase();//获取判断用的对象
              if (ua.match(/MicroMessenger/i) == "micromessenger") {
                //在微信中打开
                window.WechatAuthorize();
                return 
              }
              if(ua.match(/WeiBo/i) == "weibo") {
                 //在新浪微博客户端打开
                 window.WeiboAuthorize();
                 return 
              }
             
              this.setState({
                isLogin:true
              })

        }
    }

    toggleHandl(){
      let htmlStr = this.state.htmlStr;
     
      if(this.state.toggle){
          this.setState({
             // html:htmlStr.substring(0,26),
              toggle:false
          })
           this.refs.htmlbox.style.height = "0.4rem"
      }else{
          this.setState({
              //html:htmlStr,
              toggle:true
          })
          this.refs.htmlbox.style.height = "auto"
         
      }
    }


	render(){
		let { 
      courselist,
      nowIndex,
      worklist,
      mywork,
      commentlist,
      showmask,
      html,
      desc,
      title,
      userimg,
      username,
      videoSrc,
      CommentsCount,
      AppUserId,
      toggle,
      showBtn
    } = this.state;
 
  
   
		return(
            <div className="detail">
                <div className="title">{title}</div>
                
                <div className="content">
                    <div className="top">
                        <div className="video">                
                            <iframe frameBorder="0" src={videoSrc} allowFullScreen></iframe>
                            {/*<video src={videoSrc} controls="controls" ref="video" autoPlay></video>*/}
                            {/*<img src="https://jixiuapp-staging-proxy.azurewebsites.net/blob/349f9a1e-6e67-11ea-aa76-00155d45d897/99533477-dfa5-4ecd-b3d3-a1ab7abc4b3b.jpeg" alt=""/>*/}
                            {/*<div className="videomask"></div><button className="play"></button>*/}
                        </div>
                        <dl>
                           <dt><img src={userimg} alt=""/></dt>
                           <dd>{username}</dd>
                        </dl>
                         
                        <div className="desc">
                            {this.state.showDown?<span className={toggle?"up":"down"} onClick={this.toggleHandl.bind(this)}></span>:null}
                            
                            <div dangerouslySetInnerHTML={{__html: html}} ref="htmlbox"></div>
                        </div>
                    </div>

                    <div className="course">
                        <h3>
                           <span>课程系列 ({courselist.length})</span>
                           <em></em>
                        </h3>
                        
                        <div className="courselist" ref="courselist"> 
                            <ul style={{"width":courselist.length*2.7+"rem"}}>
                                {courselist.map((item,index)=>{
                                	return  <li className={index===nowIndex?"active":""}
                                	            onClick={this.changeCourselist.bind(this,index,item.link)}
                                	            key={index} >
                                	            {this.toZero(index+1)}{item.title}
                                	        </li>
                                })}

                                
                            </ul>
                        </div>     
                    </div>


                    <div className="goodwork">
                        {worklist.length!==0?<div className="hd">
                            <h3><i></i>优秀作业</h3>
                            {worklist.length>5?<span onClick={()=>{this.props.history.push("/fanscourse/assignments/"+this.props.match.params.id)}}>更多<i></i></span>:null}
                        </div>:null}
                        

                        <div className="worklist" ref="worklist">
                             <ul style={{"width":worklist.slice(0,5).length*2.7+"rem"}}>
                               {
                               	worklist.slice(0,5).map((item,index)=>{
                               		return <li  key={index} onClick={()=>{this.props.history.push("/fanscourse/workdetail/"+item.PostId)}}>
                               		   <div className="img">
                                          {item.PhotoList.length!==0?<img src={item.PhotoList[0]?item.PhotoList[0].ThumbnailUrl:""} alt=""/>:null}
                                          {item.VideoList.length!==0?<img src={item.VideoList[0]?item.VideoList[0].ThumbnailUrl:""} alt=""/>:null}
                                          
                                          {AppUserId===item.AppUserId?<span></span>:null}
                                          
                               		   </div>
                               		   <p>
                               		      <img src={item.AppUserModel.ImageUrl} alt=""/>
                               		      <span>{item.AppUserModel.NickName}</span>
                               		   </p>
                               		</li>
                               	})
                               }
                             </ul>
                        </div>
                    </div>


                    <div className="mywork">
                        {this.state.isShow? <div className="hd">
                            <h3><i></i>我的作业</h3>
                        </div>:null}
                       

                        <div className="myworklist" ref="myworklist">
                             <ul style={{"width":worklist.length*2.7+"rem"}}>
                               {
                               	mywork.map((item,index)=>{
                               		return <li key={index} onClick={()=>{
                                      
                                     // if(item.IsVerified){
                                         this.props.history.push("/fanscourse/workdetail/"+item.PostId)
                                     // }
                                     
                                     }}>
                               		   <div className="img">
                                          {item.PhotoList.length!==0?<img src={item.PhotoList[0]?item.PhotoList[0].ThumbnailUrl:""} alt=""/>:null}
                                          {item.VideoList.length!==0?<img src={item.VideoList[0]?item.VideoList[0].ThumbnailUrl:""} alt=""/>:null}
                                          <span></span>
                                     </div>
                               		</li>
                               	})
                               }
                             </ul>
                        </div>
                       
                        {mywork.length===0 && this.state.isShow?<div><div className="topost" onClick={this.toPost.bind(this)}>
                             <i></i>交作业
                        </div>
                        <p className="ask">{desc}</p></div>:null}
                        
                    </div>


                    <div className="commentlist">
                        <div className="hd">
                            <h3>全部评论 ({CommentsCount})</h3>
                            <em></em>
                            {CommentsCount>3?<span onClick={()=>{this.setState({
                                                                       showmask:true
                                                                     },()=>{
                                                                       this.loadComment()
                                                                     })
                                                                   }}>更多<i></i></span>:null}
                        </div>

                        <ul>
                           {commentlist.slice(0,3).map(item=>{
                              return <li key={item.CommentId}>
                              <dl>
                                <dt><img src={item.UserModel.ImageUrl?item.UserModel.ImageUrl:defaultImg} alt=""/></dt>
                                <dd>
                                   <p>{item.UserModel.NickName}</p>
                                   <span>{item.CreateDate.split("T")[0]}</span>
                                </dd>
                              </dl>
                              <em  className={item.IsLiked?"like":""}>
                                    {item.IsLiked?<i className="active" onClick={this.UnLikeCommentHandl.bind(this,item.CommentId)}></i>:<i onClick={this.LikeCommentHandl.bind(this,item.CommentId)}></i>}
                               {item.LikesCount}</em>
                              <div>{item.Text}</div>
                           </li>
                           })}
                          
                        </ul>
                        
                        {CommentsCount===0?<p className="nodata">暂无评论，快去给老师发射你的爱心吧～</p>:null}
                        
                        
                        <span className="more" onClick={()=>{
                           if(localStorage.getItem("courseUserinfo")){
                                  this.setState({showmask:true},()=>{
                                    this.loadComment()
                                  })
                           }else{
                               var ua = navigator.userAgent.toLowerCase();//获取判断用的对象
                               if (ua.match(/MicroMessenger/i) == "micromessenger") {
                                  //在微信中打开
                                  window.WechatAuthorize();
                                  return 
                               }
                               if (ua.match(/WeiBo/i) == "weibo") {
                                   //在新浪微博客户端打开
                                   window.WeiboAuthorize();
                                   return 
                               }
                               
                               this.setState({
                                  isLogin:true
                               })
                  
                           }
                          
                         
                        }}>发表评论<i></i></span>
                        

                        
                    </div>
                </div>
                
               

               {showmask?<div className="mask" >
                    <div className="maskbox" onClick={()=>{this.setState({showmask:false})}}></div>
                    <div className="commentbox">
                      <div className="commentlist">
                        <div className="hd" style={{"paddingTop":"0.3rem"}}>
                            <h3 style={{"fontSize":"0.3rem"}}>全部评论 ({CommentsCount})</h3>
                            <em style={{"width": "1.2rem",    "bottom": "0.0rem"}}></em>
                        </div>
                        
                        <div className="commentwrap" ref="commentwrap">
                        <ul>
                           {commentlist.map(item=>{
                              return <li key={item.CommentId}>
                              <dl>
                                <dt><img src={item.UserModel.ImageUrl?item.UserModel.ImageUrl:defaultImg} alt=""/></dt>
                                <dd>
                                   <p>{item.UserModel.NickName}</p>
                                   <span>{item.CreateDate.split("T")[0]}</span>
                                </dd>
                              </dl>
                              <em  className={item.IsLiked?"like":""}>
                                    {item.IsLiked?<i className="active" onClick={this.UnLikeCommentHandl.bind(this,item.CommentId)}></i>:<i onClick={this.LikeCommentHandl.bind(this,item.CommentId)}></i>}
                               {item.LikesCount}</em>
                              <div>{item.Text}</div>
                           </li>
                           })}
                        </ul>
                       </div>

                      </div>
                      


                      <div className="form">
                          <p>
                            <i></i>
                            <input type="text" 
                            placeholder="写下你的评论…" 
                            value={this.state.msg}
                            onChange={(ev)=>{
                              this.setState({
                                msg:ev.target.value
                              })
                            }}
                            onClick={()=>{
                              if(localStorage.getItem("courseUserinfo")){  //已经登录
                                   let token =JSON.parse(localStorage.getItem("courseUserinfo")).AccessToken;
                                   getUserInfo(token).then(res=>{
                                       if(res.data.PhoneNumber==""){//未绑定手机号
                                           this.props.history.push("/fanscourse/bindphone")
                                       }
                                   })
                              }else{  //没有登录
                                    var ua = navigator.userAgent.toLowerCase();//获取判断用的对象
                                    if (ua.match(/MicroMessenger/i) == "micromessenger") {
                                       //在微信中打开
                                       window.WechatAuthorize();
                                       return 
                                    }
                                    if (ua.match(/WeiBo/i) == "weibo") {
                                      //在新浪微博客户端打开
                                        window.WeiboAuthorize();
                                        return 
                                    }
                                    
                                    this.setState({
                                       isLogin:true
                                    })
                              }
                            }}/>
                          </p>
                          <span onClick={this.addComment.bind(this)}>发送</span>
                       </div>
                    </div>
                </div>:null}
               
                
                <span className="goindex" onClick={()=>{this.props.history.push("/fanscourse")}}></span>


                {this.state.isLogin?<Login closeModal={this.closeModal.bind(this)}/>:null}
                
                {this.state.showLoading?<div className="detail-loading"><p>{this.state.loading}</p></div>:null}


                 {this.state.showTip?<Tipmsg msg={this.state.tipmsg} closeHandl={this.closeHandl.bind(this)}/>:null}
                 
                 {this.state.showload?<Loading />:null}
            </div>
		)
	}
}


export default Index